﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.NET.Core.Service;
using Admin.NET.Core;
using Admin.Net.InformationPlatform.Entity.Maintenance;
using Admin.Net.InformationPlatform.Entity;
using Admin.Net.InformationPlatform.Service.Maintenance.Dto;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Entity.ProdectFile;
using Admin.Net.InformationPlatform.Service.ProjectFile.Dto;
using Admin.Net.InformationPlatform.Entity.Equipment;
using Admin.Net.InformationPlatform.Service.Equipment.Dto;

namespace Admin.Net.InformationPlatform.Service.ProjectFile
{

    /// <summary>
    /// 华为验厂-SOP文件管理
    /// </summary>
    [ApiDescriptionSettings(groups: "HWYC", Name = "SOP文件管理", Tag = "SOP文件管理", Order = 200)]

    public class ProjectFileService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _plm;
        private SqlSugarProvider _Dilon;


        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;
        /// <summary>
        /// SOP工程文件管理
        /// </summary>
        /// <param name="db"></param>
        public ProjectFileService(ISqlSugarClient db)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100TestArea.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

        }
        //        /// <summary>
        //        ///  获取品名对应的工程文件列表-分页
        //        /// </summary>
        //        /// <returns></returns>
        //        [HttpPost("/HWYC/GetProjectFilePagedList")]
        //        public async Task<SqlSugarPagedList<HW_PRODECT_FILE>> GetMouldPagedList(ProjectFileInput input)
        //        {

        //            var output = await _SjDb.Queryable<HW_PRODECT_FILE>()
        //.Where(l => l.ISDELETE == 0)
        //.WhereIF(!string.IsNullOrEmpty(input.PRODECTNAME), (l) => (l.PRODECTNAME.Contains(input.PRODECTNAME)))//品名

        //.OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
        //.Select(l => new HW_PRODECT_FILE
        //{
        //    ID = l.ID,
        //    PRODECTNAME = l.PRODECTNAME,
        //    FILEPATH = l.FILEPATH,
        //    CREATETIME =l.CREATETIME,
        //    FILENAEM = l.FILENAEM,
        //    USERID =l.USERID,
        //    USERNAME =l.USERNAME,
        //    BBH = l.BBH


        //}).ToPagedListAsync(input.Page, input.PageSize);
        //            return output;
        //        }


        //        /// <summary>
        //        ///  获取品名对应的工程文件列表-分页（历史记录）
        //        /// </summary>
        //        /// <returns></returns>
        //        [HttpPost("/HWYC/GetProjectFileHisPagedList")]
        //        public async Task<SqlSugarPagedList<HW_PRODECT_FILE>> GetProjectFileHisPagedList(ProjectFileInput input)
        //        {
        //            var output = await _SjDb.Queryable<HW_PRODECT_FILE>()
        //.Where(l => l.ISDELETE == 1)
        //.WhereIF(!string.IsNullOrEmpty(input.PRODECTNAME), (l) => (l.PRODECTNAME==input.PRODECTNAME))//品名
        //.OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
        //.Select(l => new HW_PRODECT_FILE
        //{
        //    ID = l.ID,
        //    PRODECTNAME = l.PRODECTNAME,
        //    FILEPATH = l.FILEPATH,
        //    CREATETIME = l.CREATETIME,
        //    FILENAEM = l.FILENAEM,
        //    USERID = l.USERID,
        //    USERNAME = l.USERNAME,
        //    BBH = l.BBH


        //}).ToPagedListAsync(input.Page, input.PageSize);
        //            return output;
        //        }
        //        /// <summary>
        //        /// 增加SOP工程文件
        //        /// </summary>
        //        /// <returns></returns>
        //        [HttpPost("/HWYC/AddProjectFile")]
        //        public async Task<string> AddQuestion(HW_PRODECT_FILE[] input)
        //        {
        //            List<HW_PRODECT_FILE> list = new List<HW_PRODECT_FILE>();
        //            if (input.Count() > 0)
        //            {
        //                for(int i = 0; i < input.Count(); i++)
        //                {
        //                    //判断单据存在
        //                    int cnt = await _SjDb.Queryable<HW_PRODECT_FILE>()
        //                        .Where(a => a.PRODECTNAME == input[i].PRODECTNAME)
        //                        .Select(a => a.ID)
        //                        .CountAsync();
        //                    if (cnt != 0)//有数据时，先进行伪删除再添加
        //                    {
        //                        _SjDb.Ado.BeginTran();
        //                        int count = await _SjDb.Updateable<HW_PRODECT_FILE>()
        //                            .SetColumns(a => a.ISDELETE == 1)
        //                            .Where(a => a.PRODECTNAME == input[i].PRODECTNAME && a.ISDELETE == 0)
        //                            .ExecuteCommandAsync();
        //                    }
        //                    var details = new HW_PRODECT_FILE
        //                    {
        //                        ID = Guid.NewGuid().ToString("N"),
        //                        PRODECTNAME = input[i].PRODECTNAME,
        //                        FILEPATH = input[i].FILEPATH,
        //                        ISDELETE = 0,
        //                        CREATETIME = DateTime.Now,
        //                        FILENAEM = input[i].FILENAEM,
        //                        USERID = _User.UserId,
        //                        USERNAME = _User.RealName,
        //                        BBH = "V" + (cnt + 1).ToString(),
        //                    };
        //                    list.Add(details);

        //                }
        //            }
        //            #region 插入事务
        //            try
        //            {
        //                //开启事务
        //                _SjDb.Ado.BeginTran();
        //                int cnt = await _SjDb.Insertable<HW_PRODECT_FILE>(list).ExecuteCommandAsync();

        //                if (cnt == 0)
        //                {
        //                    throw Oops.Oh($"新建任务失败！");
        //                }
        //                //提交事务
        //                _SjDb.Ado.CommitTran();
        //                return "插入成功";
        //            }
        //            catch (Exception e)
        //            {
        //                //回滚事务
        //                _SjDb.Ado.RollbackTran();
        //                throw Oops.Oh($"异常：{e.Message}");
        //            }
        //            #endregion

        //        }
        /// <summary>
        /// 获取品名对应的工程文件列表-分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/HWYC/GetProjectFilePagedList")]
        public async Task<SqlSugarPagedList<FILELIST>> GetProjectFilePagedList(GetFileList input)
        {



            var output = await _SjDb.Queryable<HW_PRODECT_FILE>()
            .Where(l => l.ISDELETE == 0)
            .WhereIF(!string.IsNullOrEmpty(input.PRODUCTNAME), (l) => (l.PRODECTNAME.Contains(input.PRODUCTNAME)))//品名
            .OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
            .Select(l => new FILELIST
            {
                ID = l.ID,
                PRODECTNAME = l.PRODECTNAME,
                CREATETIME = l.CREATETIME,
                USERID = l.USERID,
                USERNAME = l.USERNAME,

            }).ToPagedListAsync(input.Page, input.PageSize);

            for (int i = 0; i < output.Items.Count(); i++)
            {
                output.Items.ToList()[i].FILES =  _SjDb.Queryable<HW_Prodect_File_LIST>()
            .Where(l => l.ISDELETE == 0)
            .Where(l => (l.PRODECTNAME == output.Items.ToList()[i].PRODECTNAME))//品名
             .OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
             
            .Select(l => new HW_Prodect_File_LIST
            {
                ID = l.ID,
                PRODECTNAME = l.PRODECTNAME,
                CREATETIME = l.CREATETIME,
                USERID = l.USERID,
                USERNAME = l.USERNAME,
                BBH = l.BBH,
                FILENAEM = l.FILENAEM,
                FILEPATH = l.FILEPATH,
                FID = l.FID,

            }).ToList();
            }

           

            return output;

        }
        /// <summary>
        ///  获取品名对应的工程文件列表-分页（历史记录）
        /// </summary>
        /// <returns></returns>
        [HttpPost("/HWYC/GetProjectFileHisPagedList")]
        public async Task<SqlSugarPagedList<HW_Prodect_File_LIST>> GetProjectFileHisPagedList(ProjectFileInput input)
        {
            var output = await _SjDb.Queryable<HW_Prodect_File_LIST>()
.Where(l => l.ISDELETE == 1)
.WhereIF(!string.IsNullOrEmpty(input.PRODECTNAME), (l) => (l.PRODECTNAME == input.PRODECTNAME))//品名
//.OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
 .OrderBy(l => l.PRODECTNAME)
 .OrderBy(l => l.FID)
  .OrderBy(l => l.BBH)
.Select(l => new HW_Prodect_File_LIST
{
    ID = l.ID,
    PRODECTNAME = l.PRODECTNAME,
    FILEPATH = l.FILEPATH,
    CREATETIME = l.CREATETIME,
    FILENAEM = l.FILENAEM,
    USERID = l.USERID,
    USERNAME = l.USERNAME,
    BBH = l.BBH,
    FID = l.FID,


}).ToPagedListAsync(input.Page, input.PageSize);
            return output;
        }
        /// <summary>
        ///  获取单个对应的工程文件列表-分页（历史记录）
        /// </summary>
        /// <returns></returns>
        [HttpPost("/HWYC/GetFileHisPagedList")]
        public async Task<SqlSugarPagedList<HW_Prodect_File_LIST>> GetFileHisPagedList(FileListInput input)
        {
            var output = await _SjDb.Queryable<HW_Prodect_File_LIST>()
.Where(l => l.ISDELETE == 1)
.Where((l) => (l.FID == input.FID))//FID
.OrderBy(l => l.BBH, OrderByType.Desc) //版本号排序
.Select(l => new HW_Prodect_File_LIST
{
    ID = l.ID,
    PRODECTNAME = l.PRODECTNAME,
    FILEPATH = l.FILEPATH,
    CREATETIME = l.CREATETIME,
    FILENAEM = l.FILENAEM,
    USERID = l.USERID,
    USERNAME = l.USERNAME,
    BBH = l.BBH


}).ToPagedListAsync(input.Page, input.PageSize);
            return output;
        }

        /// <summary>
        /// 添加设备信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/HWYC/AddProjectFile")]
        public async Task<string> AddProjectFile(ADDFILE input)
        {
            List<HW_PRODECT_FILE> list = new List<HW_PRODECT_FILE>();
            List<HW_Prodect_File_LIST> Zilist = new List<HW_Prodect_File_LIST>();
  

            if (string.IsNullOrEmpty(input.PRODECTNAME))
             {
                 throw Oops.Oh($"请填写品名！");

             }

                    //判断单据存在
                    int cnt = await _SjDb.Queryable<HW_PRODECT_FILE>()
                        .Where(a => a.PRODECTNAME == input.PRODECTNAME)
                         .Where(l => l.ISDELETE == 0)
                        .Select(a => a.ID)
                        .CountAsync();
                    if (cnt > 0)
                    {
                        throw Oops.Oh($"任务已经存在！");
                    }
                    //    StringBuilder sb = new StringBuilder();



                    for (int j = 0; j < input.FILES.Count; j++)
                    {
                        HW_Prodect_File_LIST basicZi = new HW_Prodect_File_LIST();
                        basicZi.ID = Guid.NewGuid().ToString("N");
                        basicZi.FILENAEM = input.FILES[j].FILENAME;
                        basicZi.FILEPATH = input.FILES[j].FILEPATH;
                        basicZi.PRODECTNAME = input.PRODECTNAME.ToUpper();
                        basicZi.ISDELETE = 0;
                        basicZi.USERID = _User.UserId;
                        basicZi.USERNAME =_User.RealName;
                        basicZi.BBH ="V"+"1";
                        basicZi.CREATETIME = DateTime.Now;
                        basicZi.FID = basicZi.ID;
                        Zilist.Add(basicZi);
                    }


                    var details = new HW_PRODECT_FILE
                    {
                        ID = Guid.NewGuid().ToString("N"),
                        PRODECTNAME = input.PRODECTNAME.ToUpper(),
                        CREATETIME = DateTime.Now,
                        ISDELETE = 0,
                        USERID = _User.UserId,
                        USERNAME = _User.RealName
         

                    };
                    list.Add(details);

           
      
            #region 插入事务
            try
            {
                //开启事务
                _SjDb.Ado.BeginTran();
                int cnt1 = await _SjDb.Insertable<HW_PRODECT_FILE>(list).ExecuteCommandAsync();
                int cnt2 = await _SjDb.Insertable<HW_Prodect_File_LIST>(Zilist).ExecuteCommandAsync();

                if (cnt1 == 0 || cnt2 == 0)
                {
                    throw Oops.Oh($"新建任务失败！");
                }
                //提交事务
                _SjDb.Ado.CommitTran();
                return "插入成功";
            }
            catch (Exception e)
            {
                //回滚事务
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
            #endregion

        }
        /// <summary>
        /// 更改SOP信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/HWYC/UpdateProjectFile")]
        public async Task<string> UpdateProjectFile(UPDATEFILE input)
        {

            if (string.IsNullOrEmpty(input.PRODUCTNAME))
            {
                throw Oops.Oh($"请填写完整参数！");
            }
            DateTime dateTime = DateTime.Now;

            //判断单据存在
            int cnt = await _SjDb.Queryable<HW_PRODECT_FILE>()
                .Where(a => a.ID == input.ID)
                 .Where(l => l.ISDELETE == 0)
                .Select(a => a.ID)
                .CountAsync();
            if (cnt == 0)
            {
                throw Oops.Oh($"任务不存在！");
            }
            else
            {
                //提交
                try
                {
                    //判断要修改的数据是否存在
                    int cnt1 = await _SjDb.Queryable<HW_PRODECT_FILE>()
                        .Where(a => a.PRODECTNAME == input.PRODUCTNAME)
                        .Where(a => a.ID != input.ID)
                         .Where(l => l.ISDELETE == 0)
                        .Select(a => a.ID)
                        .CountAsync();
                    if (cnt1 != 0)
                    {
                        throw Oops.Oh($"该品名已存在，不可修改！");
                    }
                    _SjDb.Ado.BeginTran();

                    int count = await _SjDb.Updateable<HW_PRODECT_FILE>()
                         .SetColumns(a => a.PRODECTNAME == input.PRODUCTNAME)
                         .Where(a => a.ID == input.ID)
                        .ExecuteCommandAsync();


                    List<HW_Prodect_File_LIST> list = new List<HW_Prodect_File_LIST>();
                    //文件处理
                    if (input.FILES.Count > 0) { 
                    for (int i = 0; i < input.FILES.Count; i++)
                    {
                        if (!string.IsNullOrEmpty(input.FILES[i].ID))//有数据时，先进行伪删除再添加
                        {
                            _SjDb.Ado.BeginTran();

                            var data = _SjDb.Queryable<HW_Prodect_File_LIST>()
    .Where(a => a.ID == input.FILES[i].ID)
    .Select(a => a.BBH).ToList();
                            var fiddata = _SjDb.Queryable<HW_Prodect_File_LIST>()
.Where(a => a.ID == input.FILES[i].ID)
.Select(a => a.FID).ToList();
                            int count1 = await _SjDb.Updateable<HW_Prodect_File_LIST>()
                                .SetColumns(a => a.ISDELETE == 1)
                                .Where(a => a.ID == input.FILES[i].ID && a.ISDELETE == 0)
                                .ExecuteCommandAsync();
                            if (!string.IsNullOrEmpty(input.FILES[i].FILENAME) && !string.IsNullOrEmpty(input.FILES[i].FILEPATH))//数据不为空时修改数据，否则为删除
                            {
                                string ID = Guid.NewGuid().ToString("N");
                                var details = new HW_Prodect_File_LIST
                                {
                                    ID = ID,
                                    FILENAEM = input.FILES[i].FILENAME,
                                    FILEPATH = input.FILES[i].FILEPATH,
                                    PRODECTNAME = input.PRODUCTNAME.ToUpper(),
                                    ISDELETE = 0,
                                    USERID = _User.UserId,
                                    USERNAME = _User.RealName,
                                    BBH = "V" + (Convert.ToInt32(data[0].Substring(1)) + 1).ToString(),
                                    CREATETIME = DateTime.Now,
                                    FID = fiddata[0],
                                };
                                list.Add(details);

                            }

                        }
                        else
                        {
                            string ID = Guid.NewGuid().ToString("N");
                            var details = new HW_Prodect_File_LIST
                            {
                                ID = ID,
                                FILENAEM = input.FILES[i].FILENAME,
                                FILEPATH = input.FILES[i].FILEPATH,
                                PRODECTNAME = input.PRODUCTNAME.ToUpper(),
                                ISDELETE = 0,
                                USERID = _User.UserId,
                                USERNAME = _User.RealName,
                                BBH = "V" + "1",
                                CREATETIME = DateTime.Now,
                                FID = ID
                            };
                            list.Add(details);
                        }
                    }
                        int cnt2 = await _SjDb.Insertable<HW_Prodect_File_LIST>(list).ExecuteCommandAsync();
                    }
                    

                    //if (count != 1 || cnt2 == 0)
                    //{
                    //    throw Oops.Oh("修改失败！");
                    //}
                    _SjDb.Ado.CommitTran();
                    return "修改成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }

            }

        }

        /// <summary>
        /// SOP工程文件删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/HWYC/DeleteProductName")]
        public async Task<string> DeleteProductName(ProjectFileDelete input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<HW_PRODECT_FILE>()
                .Where(a => a.ID == input.ID)
                .Select(a => a.ID)
                .CountAsync();
            if (cnt == 0)
            {
                throw Oops.Oh("任务不存在，驳回！");
            }
            else
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    int count = await _SjDb.Updateable<HW_PRODECT_FILE>()
                        .SetColumns(a => a.ISDELETE == 1)
                        .Where(a => a.ID == input.ID)
                        .ExecuteCommandAsync();

                    if (count != 1)
                    {
                        throw Oops.Oh("删除失败！");
                    }
                    _SjDb.Ado.CommitTran();
                    return "删除成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }
        }
        /// <summary>
        /// 获取品名下拉框列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("/SRM/GetPMList")]
        public async Task<object> GetPMPHList(GetPMList input)
        {
            return _T100Db.Ado.SqlQuery<PmPhList>($@"
                    select 
distinct imaal003 value
from dsdata.imaal_t  l
left join dsdata.imaa_t a on l.imaal001 = a.imaa001 and l.imaalent = a.imaaent
where IMAA010='03' and IMAASTUS='Y' and 
IMAAENT='8' and imaal003 like '%{input.ProductNAME}%'
                    ").ToJson();
        }
    }
}
